package com.tools.helper;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.tbruyelle.rxpermissions3.RxPermissions;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import io.reactivex.rxjava3.disposables.Disposable;


public class MainActivity extends AppCompatActivity {

    Handler handler = new Handler();
	TextView textView;
	BleBuffer mBleBuffer = new BleBuffer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
		System.out.println("aa== " + Integer.toHexString(~159));
        findViewById(R.id.btn1).setOnClickListener(v -> {
            test();
        });
        findViewById(R.id.btn2).setOnClickListener(v -> {
			conn();
        });
		findViewById(R.id.btn4).setOnClickListener(v -> {
			if (gatt != null) {
				gatt.disconnect();
				gatt.close();
			}
			gatt = null;
		});
		findViewById(R.id.btn5).setOnClickListener(v -> {

		});
		textView = findViewById(R.id.tv_text);

		//service
		// 00001800-0000-1000-8000-00805f9b34fb
		// 00001801-0000-1000-8000-00805f9b34fb
		// 0000180a-0000-1000-8000-00805f9b34fb
		// 0000fff0-0000-1000-8000-00805f9b34fb
		findViewById(R.id.btn3).setOnClickListener(v -> {
			List<BluetoothGattCharacteristic> gcList = getNotify();
			System.out.println("aaaaaaaaa========= "+gcList.size());
			for (BluetoothGattCharacteristic gc : gcList) {
				if (BleParser.getHexUUID(gc.getUuid()) == 0xFFF1) {
					gatt.setCharacteristicNotification(gc, true);
					BluetoothGattDescriptor descr = gc.getDescriptors().get(0);
					descr.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
					gatt.writeDescriptor(descr);
				}
			}
		});
		BluetoothAdapter.getDefaultAdapter().enable();
    }

	private List<BluetoothGattCharacteristic> getNotify() {
		List<BluetoothGattCharacteristic> data = new ArrayList<>();
		List<BluetoothGattService> list = gatt.getServices();
		System.out.println("aa " + list.size());
		for (BluetoothGattService gs : list) {
			List<BluetoothGattCharacteristic> gcList = gs.getCharacteristics();
			for (BluetoothGattCharacteristic gc : gcList) {
				System.out.println("============pro " + gc.getProperties() + "  " + (gc.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY));
				if ((gc.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
					data.add(gc);
				}
			}
		}
		return data;
	}

	@Override
	protected void onStart() {
		super.onStart();
		String[] permissions = {
				Manifest.permission.ACCESS_FINE_LOCATION,
				Manifest.permission.ACCESS_COARSE_LOCATION
		};
		RxPermissions rxPermissions = new RxPermissions(this);
		Disposable d = rxPermissions.request(permissions)
				.subscribe(isTrue -> {

				}, Throwable::printStackTrace);
	}

	BluetoothGatt gatt;
	private void conn() {
		if (scanResult == null) {
			Toast.makeText(this, "未发现设备", Toast.LENGTH_SHORT).show();
			return;
		}
		gatt = scanResult.getDevice().connectGatt(this, true, new BluetoothGattCallback() {
			@Override
			public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
				System.out.println("aaaaaaaaaaa====== " + newState);
				if (newState == BluetoothGatt.STATE_CONNECTED) {
					gatt.discoverServices();
				}
			}

			@Override
			public void onServicesDiscovered(BluetoothGatt gatt, int status) {
				System.out.println("aaaaaaaaaaa11====== " + status);
				if (status == BluetoothGatt.GATT_SUCCESS) {
					gatt.requestMtu(36);
					//根据指定的服务uuid获取指定的服务
					/*BluetoothGattService gattService = gatt.getService(UUID.fromString(mServiceUUID));
					//根据指定特征值uuid获取指定的特征值A
					mGattCharacteristicA = gattService.getCharacteristic(UUID.fromString(mReadCharacteristicUUID));

					//设置特征A通知,即设备的值有变化时会通知该特征A，即回调方法onCharacteristicChanged会有该通知
					mBluetoothGatt.setCharacteristicNotification(mGattCharacteristicA , true);

					//获取特征值其对应的通知Descriptor
					BluetoothGattDescriptor descriptor = mGattCharacteristicA.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
					//写入你需要传递给外设的特征的描述值（即传递给外设的信息）
					descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
					//通过GATT实体类将，特征值写入到外设中。成功则在 onDescriptorWrite 回调
					mBluetoothGatt.writeDescriptor(descriptor);*/
				}
			}

			@Override
			public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
				System.out.println("aaaaaaaaaaa22====== " + status);
			}

			@Override
			public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
				System.out.println("aaaaaaaaaaa33====== " + status);
			}

			@Override
			public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
				mBleBuffer.set(characteristic.getValue());
				//System.out.println(Arrays.toString(buffer.value));
				runOnUiThread(()-> {
					textView.setText("电量: " + mBleBuffer.getBatteryLevel() + "%  温度: " + mBleBuffer.getInternal() + "℃   环境温度: " + mBleBuffer.getAmbient() + "℃");
				});
				//System.out.println(BleParser.bytesToHex(characteristic.getValue()));
				//System.out.println(BleParser.calculateChecksum(mBleBuffer.payload));
				//System.out.println("onCharacteristicChanged====== " + buffer.getBatteryLevel() + "  " + buffer.getInternal() + "℃   " + buffer.getAmbient() + "℃");
			}

			//a5 02 6c 19 00 4b   01 b1 41 00000000 64 00000000 02 0000 1a 01 13 01 000000000000
			//a5 02 6d 19 00 4c   01 b1 41 00000000 64 00000000 02 0000 19 01 12 01 000000000000
			//a5 02 6e 19 00 4b   01 b1 41 00000000 64 00000000 02 0000 19 01 12 01 000000000000

			@Override
			public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
				System.out.println("aaaaaaaaaaa33====== " + status);
				runOnUiThread(()-> {
					Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
				});
			}

			@Override
			public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
				System.out.println("aaaaaaaaaaa44====== " + status);
			}

			@Override
			public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
				System.out.println("aaaaaaaaaaa55====== " + status);
			}
		});
	}

    private void test() {
		BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
		boolean aa = adapter.enable();
		System.out.println("=============aa " + adapter.isEnabled() + " " + aa);
		BluetoothLeScanner scanner = adapter.getBluetoothLeScanner();
		if (scanner == null) {
			Toast.makeText(this, "不支持", Toast.LENGTH_SHORT).show();
			return;
		}
		scanner.startScan(new ScanCallback() {
			@Override
			public void onScanResult(int callbackType, ScanResult result) {
				if (result.getDevice().getName() != null && result.getDevice().getName().length() > 0) {
					if (result.getDevice().getName().contains("BTS")) {
						scanResult = result;
						System.out.println(result.getDevice().getName());
						scanner.stopScan(this);
						// 23:51:00:00:00:23
						byte[] bb = ByteBuffer.wrap(result.getScanRecord().getBytes()).order(ByteOrder.LITTLE_ENDIAN).array();
						System.out.println(Arrays.toString(bb));
						System.out.println(new BleParser().bytesToHex(bb));
						textView.setText(result.getDevice().getName());
						Toast.makeText(getApplication(), "扫描成功", Toast.LENGTH_SHORT).show();
					}
				}
			}

			@Override
			public void onScanFailed(int errorCode) {
				System.out.println("aaa err === " + errorCode);
			}
		});
    }

	ScanResult scanResult;

}
